<template>
    <div id="menu-main">
        <div class="menuList-herd">
            <div>
                <el-form :inline="true" :model="paging" class="demo-form-inline">
                    <el-form-item v-for="item in menuBtns" :key="item.id">
                        <el-button v-if="CREATE == item.icon || DELETE == item.icon" :type="item.icon"
                            @click="clickBtn(item.icon)">
                            {{ item.menuName }}</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-input v-model="paging.menuName" placeholder="路由名称"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="onReSetSeach">重置</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="init">查询</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

        <div class="user-body">
            <el-table ref="multipleTable" tooltip-effect="dark" @selection-change="handleSelectionChange"
                :data="pagingData.totalList" style="width: 100%" row-key="id"
                :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
                <el-table-column type="selection" width="55" :selectable="checkboxInit"> </el-table-column>
                <el-table-column prop="id" label="id" width="100"></el-table-column>
                <el-table-column prop="menuName" label="路由菜单名称" width="180" align="center"></el-table-column>
                <el-table-column prop="path" label="路由地址" width="180" align="center"></el-table-column>
                <el-table-column prop="component" label="组件路径" width="150" align="center"></el-table-column>
                <el-table-column prop="orderNum" label="排序" width="100" align="center"></el-table-column>
                <el-table-column prop="icon" label="图标" width="100" align="center">
                    <template slot-scope="scope">
                        <div v-if="scope.row.menuType == 'F'">
                            {{ scope.row.icon }}
                        </div>
                        <div v-else>
                            <i :class="'el-icon-' + scope.row.icon"></i>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column prop="menuType" label="菜单类型" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.menuType == 'M'">目录</el-tag>
                        <el-tag v-if="scope.row.menuType == 'C'" type="success">菜单</el-tag>
                        <el-tag v-if="scope.row.menuType == 'F'" type="info">按钮</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="status" label="是否开启" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.status == '0'" type="success">开启</el-tag>
                        <el-tag v-else type="info">关闭</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="visible" label="是否显示" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.visible == '0'" type="success">显示</el-tag>
                        <el-tag v-else type="info">隐藏</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="sysMenuType" label="路由类型" width="100" align="center">
                    <template slot-scope="scope">
                        <el-tag v-if="scope.row.sysMenuType == '00'">系统</el-tag>
                        <el-tag v-if="scope.row.sysMenuType == '01'" type="info">普通</el-tag>
                    </template>
                </el-table-column>
                <el-table-column prop="remark" label="备注" width="180" align="center">
                </el-table-column>
                <el-table-column fixed="right" label="操作" min-width="120" align="center">
                    <template slot-scope="scope" v-if="isSysDef(userInfo.userType) && !isSysDef(scope.row.sysMenuType)">
                        <div class="btns" v-for="(item, index) in menuBtns" :key="index">
                            <el-button type="text" size="small" v-if="item.icon == UPDATE || item.icon == DELETE"
                                @click="handleClick(item.icon, scope.row)" :style="getButtonStyle(item.icon)">{{
                                    item.menuName }}</el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div v-if="pagingData && pagingData.totalList && pagingData.totalList.length > 0">
                <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
                    :current-page="pagingData.currentPage" :page-sizes="[10, 20, 30, 40]" :page-size="10"
                    layout="total, sizes, prev, pager, next, jumper" :total="pagingData.total">
                </el-pagination>
            </div>
        </div>

        <el-dialog title="添加路由" :visible.sync="dialogTableAddVisible">
            <el-form :model="addForm" ref="addForm">
                <el-form-item label="上级菜单路由" prop="parentId" :label-width="formLabelWidth" :required="true"
                    v-if="'C' == addForm.menuType || 'F' == addForm.menuType">
                    <treeselect v-model="addForm.parentId" :options="pagingMenuData" :normalizer="normalizer"
                        :show-count="true" placeholder="选择上级菜单" />
                </el-form-item>
                <el-form-item label="类型" prop="menuType" :label-width="formLabelWidth" :required="true">
                    <el-radio-group v-model="addForm.menuType">
                        <el-radio :label="'M'">目录</el-radio>
                        <el-radio :label="'C'">菜单</el-radio>
                        <el-radio :label="'F'">按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="addForm.menuType == 'M' ? '目录图标' : addForm.menuType == 'C' ? '菜单图标' : '按钮图标'"
                    prop="icon" :label-width="formLabelWidth"
                    v-if="'C' == addForm.menuType || 'F' == addForm.menuType || 'M' == addForm.menuType">
                    <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                        <IconSelect ref="iconSelect" @selected="selected" :active-icon="addForm.icon"
                            :type="addForm.menuType" />
                        <el-input slot="reference" v-model="addForm.icon" placeholder="点击选择图标">
                            <i v-if="addForm.icon" slot="prefix" :class="'el-icon-' + addForm.icon" style="width: 25px;" />
                            <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                        </el-input>
                    </el-popover>
                </el-form-item>
                <el-form-item :label="addForm.menuType == 'M' ? '目录名称' : addForm.menuType == 'C' ? '菜单名称' : '按钮名称'"
                    prop="menuName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="addForm.menuName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" prop="orderNum" :label-width="formLabelWidth" :required="true">
                    <el-input-number v-model="addForm.orderNum" controls-position="right" @change="handleChange"
                        :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="路由地址" prop="path" :label-width="formLabelWidth"
                    v-if="'C' == addForm.menuType || 'M' == addForm.menuType"
                    :required="'C' == addForm.menuType || 'M' == addForm.menuType">
                    <el-input v-model="addForm.path" autocomplete="off" placeholder="userList(path)"></el-input>
                </el-form-item>
                <el-form-item label="组件路径" prop="component" :label-width="formLabelWidth" v-if="'C' == addForm.menuType"
                    :required="'C' == addForm.menuType">
                    <el-input v-model="addForm.component" autocomplete="off" placeholder="user/list(component)"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="perms" :label-width="formLabelWidth" v-if="'F' == addForm.menuType"
                    :required="'F' == addForm.menuType">
                    <el-input v-model="addForm.perms" autocomplete="off" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                    <el-input v-model="addForm.remark" autocomplete="off" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="是否外链" prop="isFrame" :label-width="formLabelWidth" v-if="'M' == addForm.menuType">
                    <el-radio-group v-model="addForm.isFrame">
                        <el-radio :label="0">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否缓存" prop="isCache" :label-width="formLabelWidth" v-if="'C' == addForm.menuType">
                    <el-radio-group v-model="addForm.isCache">
                        <el-radio :label="0">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="显示状态" prop="visible" :label-width="formLabelWidth"
                    v-if="'C' == addForm.menuType || 'M' == addForm.menuType">
                    <el-radio-group v-model="addForm.visible">
                        <el-radio :label="'0'">显示</el-radio>
                        <el-radio :label="'1'">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="addForm.menuType == 'M' ? '目录状态' : addForm.menuType == 'C' ? '菜单状态' : '按钮状态'"
                    prop="status" :label-width="formLabelWidth"
                    v-if="'C' == addForm.menuType || 'F' == addForm.menuType || 'M' == addForm.menuType">
                    <el-radio-group v-model="addForm.status">
                        <el-radio :label="'0'">正常</el-radio>
                        <el-radio :label="'1'">停用</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onSave">保存</el-button>
            </div>
        </el-dialog>

        <el-dialog title="编辑路由" :visible.sync="dialogTableEditVisible">
            <el-form :model="editForm" ref="editForm">
                <el-form-item label="是否修改路由" :label-width="formLabelWidth"
                    v-if="editForm.menuType == 'F' || editForm.menuType == 'C'">
                    <el-switch v-model="eidtDeptDisPlay"></el-switch>
                    <el-tag style="margin-left: 30px">当前路由 {{ editForm.parentName == '' ? '顶级' : editForm.parentName
                    }}</el-tag>
                </el-form-item>
                <el-form-item label="上级菜单路由" prop="parentId" :label-width="formLabelWidth" :required="true"
                    v-if="eidtDeptDisPlay && (editForm.menuType == 'F' || editForm.menuType == 'C')">
                    <treeselect v-model="editForm.parentId" :options="pagingMenuData" :normalizer="normalizer"
                        :show-count="true" placeholder="选择上级菜单" />
                </el-form-item>
                <el-form-item label="菜单类型" prop="menuType" :label-width="formLabelWidth" :required="true">
                    <el-radio-group v-model="editForm.menuType">
                        <el-radio :label="'M'">目录</el-radio>
                        <el-radio :label="'C'">菜单</el-radio>
                        <el-radio :label="'F'">按钮</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="editForm.menuType == 'M' ? '目录图标' : editForm.menuType == 'C' ? '菜单图标' : '按钮图标'"
                    prop="icon" :label-width="formLabelWidth"
                    v-if="'C' == editForm.menuType || 'F' == editForm.menuType || 'M' == editForm.menuType">
                    <el-popover placement="bottom-start" width="460" trigger="click" @show="$refs['iconSelect'].reset()">
                        <IconSelect ref="iconSelect" @selected="selected" :active-icon="editForm.icon"
                            :type="addForm.menuType" />
                        <el-input slot="reference" v-model="editForm.icon" placeholder="点击选择图标">
                            <i v-if="editForm.icon" slot="prefix" :class="'el-icon-' + editForm.icon"
                                style="width: 25px;" />
                            <i v-else slot="prefix" class="el-icon-search el-input__icon" />
                        </el-input>
                    </el-popover>
                </el-form-item>
                <el-form-item :label="editForm.menuType == 'M' ? '目录名称' : editForm.menuType == 'C' ? '菜单名称' : '按钮名称'"
                    prop="menuName" :label-width="formLabelWidth" :required="true">
                    <el-input v-model="editForm.menuName" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="显示顺序" prop="orderNum" :label-width="formLabelWidth" :required="true">
                    <el-input-number v-model="editForm.orderNum" controls-position="right" @change="handleChange"
                        :min="1"></el-input-number>
                </el-form-item>
                <el-form-item label="路由地址" prop="path" :label-width="formLabelWidth"
                    v-if="'C' == editForm.menuType || 'M' == editForm.menuType"
                    :required="'C' == editForm.menuType || 'M' == editForm.menuType">
                    <el-input v-model="editForm.path" autocomplete="off" placeholder="userList(path)"></el-input>
                </el-form-item>
                <el-form-item label="组件路径" prop="component" :label-width="formLabelWidth" v-if="'C' == editForm.menuType"
                    :required="'C' == editForm.menuType">
                    <el-input v-model="editForm.component" autocomplete="off" placeholder="user/list(component)"></el-input>
                </el-form-item>
                <el-form-item label="权限字符" prop="perms" :label-width="formLabelWidth" v-if="'F' == editForm.menuType"
                    :required="'F' == editForm.menuType">
                    <el-input v-model="editForm.perms" autocomplete="off" placeholder=""></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remark" :label-width="formLabelWidth">
                    <el-input v-model="editForm.remark" autocomplete="off" type="textarea"></el-input>
                </el-form-item>
                <el-form-item label="是否外链" prop="isFrame" :label-width="formLabelWidth" v-if="'M' == editForm.menuType">
                    <el-radio-group v-model="editForm.isFrame">
                        <el-radio :label="0">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否缓存" prop="isCache" :label-width="formLabelWidth" v-if="'C' == editForm.menuType">
                    <el-radio-group v-model="editForm.isCache">
                        <el-radio :label="0">是</el-radio>
                        <el-radio :label="1">否</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="显示状态" prop="visible" :label-width="formLabelWidth"
                    v-if="'C' == editForm.menuType || 'M' == editForm.menuType">
                    <el-radio-group v-model="editForm.visible">
                        <el-radio :label="'0'">显示</el-radio>
                        <el-radio :label="'1'">隐藏</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item :label="editForm.menuType == 'M' ? '目录状态' : editForm.menuType == 'C' ? '菜单状态' : '按钮状态'"
                    prop="status" :label-width="formLabelWidth"
                    v-if="'C' == editForm.menuType || 'F' == editForm.menuType || 'M' == editForm.menuType">
                    <el-radio-group v-model="editForm.status">
                        <el-radio :label="'0'">正常</el-radio>
                        <el-radio :label="'1'">停用</el-radio>
                    </el-radio-group>
                </el-form-item>

            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="handleCancel">取 消</el-button>
                <el-button type="primary" @click="onEdit">保存</el-button>
            </div>
        </el-dialog>

    </div>
</template>

<script>
import { mapState } from 'vuex';
import { CREATE, UPDATE, DELETE, UNBIND, BIND } from "@/common/constant/Const";
import { getSecondStr, isSysDef } from "@/common/utils/strUtil";
import { menuBtnByParentId } from "@/common/utils/MenuBtnUtils";
import { menuListPaging, createMenu, deleteMenu, updateMenu } from "@/common/api/menu";
import IconSelect from "@/components/IconSelect";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
export default {
    components: {
        IconSelect,
        Treeselect
    },
    data() {
        return {
            CREATE,
            UPDATE,
            DELETE,
            UNBIND,
            BIND,
            menuBtns: [],
            paging: {
                currentPage: 1,
                pageSize: 10,
            },
            pagingData: {},
            pagingMenuData: [{
                id: 0,
                menuName: '主类目',
                children: []
            }],
            dialogTableAddVisible: false,
            addForm: {
                menuType: 'M',
                isFrame: 1,
                visible: '0',
                status: '0',
                isCache: 0
            },
            formLabelWidth: "120px",
            dialogTableEditVisible: false,
            editForm: {},
            deleteForm: {
                ids: [],
            },
            eidtDeptDisPlay: false,
        };
    },
    computed: {
        ...mapState({
            menuItem: state => state.tab.menuItem,
            userInfo: state => state.tab.userInfo,
        }),
    },
    mounted() {
        this.getMenuBtn(this.menuItem.id);
        this.init();
    },
    methods: {
        getSecondStr,
        isSysDef,
        menuBtnByParentId,
        // 获取路由
        getRoute() {
            setTimeout(() => {
                menuListPaging({ currentPage: 1, pageSize: 1000, isAll: false }).then((resp) => {
                    if (resp) {
                        // 判断isDefault是否为1，如果是，则不添加到children中
                        this.pagingMenuData[0].children = resp.data.totalList.filter(item => item.isDel != 1)
                    }
                });
            }, 500)
        },
        /** 转换菜单数据结构 */
        normalizer(node) {
            if (node.children && !node.children.length) {
                delete node.children;
            }
            return {
                id: node.id,
                label: node.menuName,
                children: node.children
            };
        },
        // 选择图标
        selected(name) {
            this.$set(this.addForm, 'icon', name);
            this.$set(this.editForm, 'icon', name);
        },
        getMenuBtn(data) {
            menuBtnByParentId(data).then((respData) => {
                this.menuBtns = respData;
            }).catch((error) => {
                console.error("Error fetching menu buttons:", error);
            });
        },
        // 查询数据
        init() {
            menuListPaging(this.paging).then((resp) => {
                this.pagingData = resp.data;
            });
        },
        // 重置
        onReSetSeach() {
            this.paging = {
                currentPage: 1,
                pageSize: 10,
            };
            this.init();
        },
        // 分页回调
        handleSizeChange(val) {
            this.paging.pageSize = val;
            this.init();
        },
        // 分页回调
        handleCurrentChange(val) {
            this.paging.currentPage = val;
            this.init();
        },
        // 是否可选择表格
        checkboxInit(row, index) {
            return !isSysDef(row.sysMenuType);
        },
        // 多选表时的回调
        handleSelectionChange(val) {
            this.deleteForm.ids = val.map(item => item.id);
        },
        // 检查是否需要应用红色字体
        getButtonStyle(perms) {
            if (this.DELETE == perms) {
                return { color: 'red' };
            }
            // 默认样式（可以是空对象，或者你可以设置其他样式）
            return {};
        },
        handleClick(type, data) {
            if (UPDATE == type) {
                // console.log(data);
                this.editForm = data;
                this.dialogTableEditVisible = true;
            }
            if (DELETE == type) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.deleteForm.ids.push(data.id);
                    this.onRemove();
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 删除
        onRemove() {
            deleteMenu(this.deleteForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                    this.getRoute()
                }
            })
        },
        clickBtn(data) {
            if (CREATE == data) {
                this.dialogTableAddVisible = true;
            }
            if (UPDATE == data) {
            }
            if (DELETE == data) {
                this.$confirm('此操作将永久删除, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.onRemove();
                }).catch(() => {
                    this.deleteForm.ids = [];
                    this.$refs.multipleTable.clearSelection();
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },
        // 确认提交
        onSave() {
            if (this.addForm.menuType == 'M') {
                delete this.addForm.parentId;
            }
            createMenu(this.addForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                    this.getRoute()
                }
            });
        },
        // 重置
        handleCancel() {
            this.dialogTableAddVisible = false;
            this.addForm = {
                menuType: 'M',
                isFrame: 1,
                visible: '0',
                status: '0',
                isCache: 0
            };
            this.dialogTableEditVisible = false;
            this.editForm = {};
            this.deleteForm.ids = [];
            this.eidtDeptDisPlay = false;
        },
        handleChange(value) {
            // console.log(value);
        },
        // 确认修改
        onEdit() {
            if (this.editForm.menuType == 'M') {
                delete this.editForm.parentId;
            }
            updateMenu(this.editForm).then((resp) => {
                if (resp) {
                    this.init();
                    this.handleCancel();
                    this.getRoute()
                }
            });
        }
    },
};
</script>